package com.mall.malllibrary.net

import com.mall.malllibrary.global.GlobalKeys
import com.mall.malllibrary.global.Mall
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit

// 创建retrofit的各个实例
object RestCreator {
    // 构建OkhttpClient私有内部单例对象,这个单例对象是供RetrofitHolder使用
    private object OkHttpHolder {
        private const val TIME_OUT = 60
        private val BUILDER = OkHttpClient.Builder()
        internal val OK_HTTP_CLIENT =
            BUILDER.connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS).build()
    }

    private object RetrofitHolder {
        // 从全局配置中取出baseURL
        private val BASE_URL =
            Mall.getConfiguration<String>(GlobalKeys.HOST)
        // 初始化retrofit实例
        internal val RETROFIT_CLIENT =
            Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(OkHttpHolder.OK_HTTP_CLIENT)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build()
    }

    // 使用 Retrofit 实例创建 API 服务接口的实例
    private object RestServiceHolder {
        internal val REST_SERVICE = RetrofitHolder
            .RETROFIT_CLIENT
            .create(RestService::class.java)
    }

    // 定义对外的属性获取  Retrofit 实例创建 API 服务接口的实例
    val restService: RestService
        get() = RestServiceHolder.REST_SERVICE

}